import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input } from 'antd';
import { history, useDispatch, useSelector } from 'umi';

import './index.less';
import '../../models/isLogin';
import './models/accountPassword';

import ForgetPassword from './forgetPassword';

type LoginProps = Record<string, any>;

const Login: React.FC<LoginProps> = () => {
  const userAccount: any = localStorage.getItem('user_account');
  const account = useSelector((state: any) => state.AccountPassword.account);
  // 此处应该调用接口判断用户是否登录成功,模拟用户信息列表
  let userList =
    (localStorage.getItem('user_account') ? JSON.parse(userAccount) : false) || account;

  const dispatch = useDispatch();
  const testLogin = (values: any) => {
    if (values.remember) {
      // 记住用户
      const { username, password } = values;

      localStorage.setItem('user_login', JSON.stringify({ username, password }));
    }
    dispatch({
      type: 'isLogin/changeLogin',
      payload: {
        username: values.username,
        isLogin: true,
      },
    });
    history.push('/home/');
  };

  const onFinish = (values: any) => {
    let ok = userList.some((item: RecordItem) => {
      return item.username === values.username && item.password === values.password;
    });
    if (ok) {
      testLogin(values);
    } else {
      alert('账号或密码错误');
    }
  };

  return (
    <div className="bg_img">
      <div className="register_box">
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item name="username" rules={[{ required: true, message: '请输入你的账号' }]}>
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="账号" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入你的密码' }]}>
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="密码"
            />
          </Form.Item>
          <Form.Item>
            <div className="flex">
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
              <ForgetPassword></ForgetPassword>
            </div>
          </Form.Item>

          <Form.Item>
            <div className="flex">
              <Button type="primary" htmlType="submit" className="login-form-button">
                登录
              </Button>
              <Button
                type="primary"
                className="login-form-button"
                onClick={() => {
                  history.push('/register');
                }}
              >
                立即注册
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
